# CardBase.gd (卡牌基类)
extends Area2D
class_name CardBase

enum State { LOCKED, ACTIVE, ELIMINATED }#{ "LOCKED": 0, "ACTIVE": 1, "ELIMINATED": 2 }

@export var layer: int = 0 #默认第1层级layer_0
#@export var collision_mask_for_children: int = 0 # 初始化为0，由CardManager动态设置
@export var card_data: CardData
@export var parents: Array[CardBase] = []
# 粒子节点引用（在场景中配置）
@onready var particles: GPUParticles2D = $GPUParticles2D

var size: Vector2:
	get:
		return Vector2(100, 150)  # 默认尺寸
			
var current_state := State.LOCKED:
	set(value):
		current_state = value
		_update_visual_state()
		
# 在初始化函数中添加空值保护
func initialize(data: CardData) -> void:
	card_data = data
	#$CardVisual/Front.texture = data.front_texture
	#$CardVisual/Back.texture = data.back_texture
		
func _ready() -> void:
	await get_tree().process_frame  # 确保子节点加载
	# 确保碰撞形状与卡牌视觉对齐
	var collision_shape := $CollisionShape2D
	var shape := RectangleShape2D.new()
	shape.size = size  # 使用卡牌的实际尺寸
	collision_shape.shape = shape
	_setup_particles()
	_update_visual_state()
		
func _setup_particles() -> void:
	if card_data:
		#particles.process_material = card_data.particle_material.duplicate()
		particles.amount = card_data.particle_amount
		particles.lifetime = card_data.particle_lifetime
		particles.modulate = card_data.particle_color

func get_rect() -> Rect2:
	return Rect2(position, size)
	
func play_eliminate_effect() -> void:
	particles.emitting = true
	await get_tree().create_timer(particles.lifetime).timeout
	queue_free()
	
func eliminate(card: CardBase) -> void:
	$AnimationPlayer.play("Eliminate")
	await $AnimationPlayer.animation_finished
	card.current_state = State.ELIMINATED
	card.play_eliminate_effect()

func _update_visual_state():
	match current_state:
		State.LOCKED:
			$CardVisual/Back.visible = true
			$CardVisual/Front.visible = false
			$CardVisual/Highlight.visible = true
		State.ACTIVE:
			$CardVisual/Back.visible = false
			$CardVisual/Front.visible = true
			$CardVisual/Highlight.visible = true
		State.ELIMINATED:
			$CardVisual/Back.visible = false
			$CardVisual/Front.visible = false
			$CardVisual/Highlight.visible = false
			

func _on_mouse_entered() -> void:
	_EventBus.card_hovered.emit(self)
	pass # Replace with function body.

func _on_mouse_exited() -> void:
	_EventBus.card_hovered_off.emit(self)
	pass # Replace with function body.
	
